package by.bsu.fpmi.bbtp;

import by.bsu.fpmi.bbtp.authentication.Role;
import by.bsu.fpmi.bbtp.authentication.User;
import by.bsu.fpmi.bbtp.dao.ClientDAO;
import by.bsu.fpmi.bbtp.dao.GoodDAO;
import by.bsu.fpmi.bbtp.dao.OrderDAO;
import by.bsu.fpmi.bbtp.dao.TransportCompanyDAO;
import by.bsu.fpmi.bbtp.dao.UserDAO;
import by.bsu.fpmi.bbtp.entities.Client;
import by.bsu.fpmi.bbtp.entities.Good;
import by.bsu.fpmi.bbtp.entities.Order;
import by.bsu.fpmi.bbtp.entities.TransportCompany;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;
import java.util.Random;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/application-context.xml")
public class DatabaseInitializer {

    private static final Random RANDOM = new Random();


    @Autowired
    private UserDAO userDAO;
    @Autowired
    private TransportCompanyDAO transportCompanyDAO;
    @Autowired
    private GoodDAO goodDao;
    @Autowired
    private OrderDAO orderDao;
    @Autowired
    private ClientDAO clientDao;

    @Test
    public void initializeAll() {
        initializeUsers();
        initializeCompanies();
        initializeClients();
        initializeGoods();
        initializeOrders();
    }

    public void initializeClients() {
        createClient("Иванов Иван", "ivanov@email.com");
        createClient("Петров Петр", "petrov@email.com");
        createClient("Сидоров Сидор", "sidorov@email.com");
        createClient("Антонов Антон", "antonov@email.com");
        createClient("Алексеев Алексей", "alekseev@email.com");
    }
    
    @Test
    public void initializeUsers() {
        for (Role role : Role.values()) {
            User user = new User(role.toString().toLowerCase(), role.toString().toLowerCase(), role);
            userDAO.save(user);
        }
    }

    @Test
    public void initializeCompanies() {
        createCompany("Доставки.BY", "contact@dostavki.by", "Минск, ул. Солнечная 5", "+375-29-689543");
        createCompany("Белкомтяжпер", "contact@belcomtyagper.by", "Минск, ул. Марсовая 2", "+375-29-5876943");
        createCompany("Пони", "support@pony.by", "Минск, ул. Лунная 42", "+375-29-7859385");
        createCompany("Курьер", "kurier@tut.by", "Минск, ул. Нептунная 84", "+375-29-3486958");
        createCompany("Грузы анлимитед", "contact@unlim.by", "Минск, ул. Меркурианская 1", "+375-29-58396758");
    }

    @Test
    public void initializeGoods() {
        createGood("Пульт управления Panasonic", 100);
        createGood("Лампа настольная", 200);
        createGood("Маркер", 10);
        createGood("Ноутбук Toshiba", 1000);
        createGood("Телефон HTC", 800);
        createGood("Открытка", 5);
        createGood("Монитор Flatron", 500);
    }
    
    @Test
    public void initializeOrders() {
        List<Good> goods = goodDao.all();
        List<Client> clients = clientDao.all();
        for (int i = 0; i < 10; i++) {
            Good good = goods.get(RANDOM.nextInt(goods.size()));
            Client client = clients.get(i % clients.size());
            createOrder(good, client);
        }
    }

    private void createOrder(Good good, Client client) {
        String[] streets = {"Кислородная", "Метанная", "Гелиевая", "Углеродная", "Водородная"};
        Order order = new Order();
        order.setClientId(client.getId());
        order.setState(Order.State.CREATED);
        order.setType(Order.Type.ORDINARY);
        order.setGoodId(good.getId());
        order.setQuantity(RANDOM.nextInt(10) + 1);
        String address = String.format("Минск, ул. %s %d",
                streets[RANDOM.nextInt(streets.length)],
                RANDOM.nextInt(20) + 1);
        order.setAddress(address);
        orderDao.save(order);
    }
    
    private void createCompany(String name, String email, String address, String phone) {
        TransportCompany company = new TransportCompany();
        company.setName(name);
        company.setAddress(address);
        company.setEmail(email);
        company.setPhoneNumber(phone);
        transportCompanyDAO.save(company);
    }

    private void createGood(String name, double price) {
        Good good = new Good();
        good.setName(name);
        good.setPrice(price);
        goodDao.save(good);
    }

    private void createClient(String name, String email) {
        Client client = new Client();
        client.setName(name);
        int value = RANDOM.nextInt(999999) + 1;
        String phoneNumber = "+375-29-" + Math.max(value, 1000000 - value);
        client.setPhoneNumber(phoneNumber);
        client.setEmail(email);
        clientDao.save(client);
    }
}
